package com.restkeeper.store.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.restkeeper.exception.BussinessException;
import com.restkeeper.store.entity.Credit;
import com.restkeeper.store.entity.CreditCompanyUser;
import com.restkeeper.store.mapper.CreditMapper;
import com.restkeeper.utils.SystemCode;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

@org.springframework.stereotype.Service("creditService")
@Service(version = "1.0.0",protocol = "dubbo")
public class CreditServiceImpl extends ServiceImpl<CreditMapper, Credit> implements ICreditService {

    @Autowired
    @Qualifier("creditCompanyUserService")
    private ICreditCompanyUserService creditCompanyUserService;

    @Override
    @Transactional
    public boolean add(Credit credit, List<CreditCompanyUser> users) {
        //保存基本信息
        save(credit);

        //判断users的内容
        if (users != null && !users.isEmpty()) {

            List<String> userName = users.stream().map(CreditCompanyUser::getUserName).collect(Collectors.toList());

            long count = userName.stream().distinct().count();

            //判断是否有重复名字
            if (userName.size() != count) {
                //有重复
                throw new BussinessException("用户名重复");
            }

            //设置关联
            users.forEach(u -> u.setCreditId(credit.getCreditId()));

            //保存数据
            creditCompanyUserService.saveBatch(users);
        }


        return true;
    }

    @Override
    public IPage<Credit> queryPage(int pageNum, int pageSize, String userName) {

        IPage<Credit> page = new Page<>(pageNum,pageSize);

        QueryWrapper<Credit> creditQueryWrapper = new QueryWrapper<>();

        if (!StringUtils.isEmpty(userName)){

            creditQueryWrapper.lambda()
                    .like(Credit::getUserName,userName)
                    .or()
                    .inSql(Credit::getCreditId,"select credit_id from t_credit_company_user where user_name like '%"+
                            StringEscapeUtils.escapeSql(userName) +"%'");
        }

        IPage<Credit> iPage = page(page, creditQueryWrapper);

        List<Credit> creditList = iPage.getRecords();

        //如果类型是公司，还需要设置相关的挂账人信息
        creditList.forEach(d->{
            if (d.getCreditType() == SystemCode.CREDIT_TYPE_COMPANY){

                QueryWrapper<CreditCompanyUser> queryWrapper = new QueryWrapper<>();

                queryWrapper.lambda().eq(CreditCompanyUser::getCreditId,d.getCreditId());

                d.setUsers(creditCompanyUserService.list(queryWrapper));
            }
        });

        iPage.setRecords(creditList);

        return iPage;
    }

    /**
     * 数据回显
     *
     * @param id
     * @return
     */
    @Override
    public Credit queryById(String id) {
        Credit credit = lambdaQuery().eq(Credit::getCreditId, id).one();

        if (credit == null) {
            throw new BussinessException("该挂账信息不存在");
        }

        //公司挂账
        if (credit.getCreditType() == SystemCode.CREDIT_TYPE_COMPANY) {
            List<CreditCompanyUser> users = creditCompanyUserService.lambdaQuery()
                    .eq(CreditCompanyUser::getCreditId, credit.getCreditId())
                    .list();

            credit.setUsers(users);
        }

        return credit;
    }

    /**
     * 修改挂账数据
     *
     * @param credit
     * @return
     */
    @Override
    public boolean updateInfo(Credit credit,List<CreditCompanyUser> users) {

        if (credit.getCreditType() == SystemCode.CREDIT_TYPE_COMPANY) {
            //挂账类型是公司，删除原有的挂账人信息
            List<CreditCompanyUser> companyUserList = creditCompanyUserService.lambdaQuery()
                    .eq(CreditCompanyUser::getCreditId, credit.getCreditId())
                    .list();

            creditCompanyUserService.removeByIds(companyUserList);
        }

        //判断users的内容
        if (users != null && !users.isEmpty()) {

            List<String> userName = users.stream().map(CreditCompanyUser::getUserName).collect(Collectors.toList());

            long count = userName.stream().distinct().count();

            //判断是否有重复名字
            if (userName.size() != count) {
                //有重复
                throw new BussinessException("用户名重复");
            }

            //设置关联
            users.forEach(u -> u.setCreditId(credit.getCreditId()));

            return creditCompanyUserService.saveBatch(users);
        }

        //挂账类型是个人，直接修改数据
        return updateById(credit);
    }

}
